<template>
  <div class="history-page">
    <!-- 查询条件区域 -->
    <el-card class="filter-card mb-4">
      <template #header>
        <div class="flex items-center justify-between">
          <span class="text-lg font-medium">查询条件</span>
          <div class="flex gap-2">
            <el-button @click="resetForm">
              <template #icon
                ><el-icon><RefreshRight /></el-icon
              ></template>
              重置
            </el-button>
            <el-button type="primary" @click="handleSearch">
              <template #icon
                ><el-icon><Search /></el-icon
              ></template>
              查询
            </el-button>
          </div>
        </div>
      </template>

      <el-form :model="queryForm" ref="queryFormRef" label-width="100px">
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="queryForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              class="w-full"
            />
          </el-form-item>
          <el-form-item label="数据类型">
            <el-select
              v-model="queryForm.dataType"
              class="w-full"
              placeholder="请选择数据类型"
            >
              <el-option
                v-for="item in dataTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="机器人">
            <el-select
              v-model="queryForm.robotId"
              class="w-full"
              placeholder="请选择机器人"
            >
              <el-option
                v-for="item in robotOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="关键字">
            <el-input
              v-model="queryForm.keyword"
              placeholder="请输入关键字"
              clearable
            />
          </el-form-item>
          <el-form-item label="数据状态">
            <el-select
              v-model="queryForm.status"
              class="w-full"
              placeholder="请选择状态"
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </div>
      </el-form>
    </el-card>

    <!-- 数据展示区域 -->
    <el-card class="data-card">
      <template #header>
        <div class="flex items-center justify-between">
          <span class="text-lg font-medium">查询结果</span>
          <div class="flex gap-2">
            <el-button @click="handleExport">
              <template #icon
                ><el-icon><Download /></el-icon
              ></template>
              导出数据
            </el-button>
            <el-button type="primary" @click="refreshData">
              <template #icon
                ><el-icon><RefreshRight /></el-icon
              ></template>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
        stripe
      >
        <el-table-column prop="date" label="时间" width="180" />
        <el-table-column prop="robotName" label="机器人" width="120" />
        <el-table-column prop="dataType" label="数据类型" width="120" />
        <el-table-column prop="value" label="数值" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="showDetail(row)"
              >详情</el-button
            >
            <el-button link type="primary" @click="handleAnalyze(row)"
              >分析</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="flex justify-end mt-4">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="数据详情"
      width="60%"
      destroy-on-close
    >
      <div class="data-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="时间">{{
            currentDetail.date
          }}</el-descriptions-item>
          <el-descriptions-item label="机器人">{{
            currentDetail.robotName
          }}</el-descriptions-item>
          <el-descriptions-item label="数据类型">{{
            currentDetail.dataType
          }}</el-descriptions-item>
          <el-descriptions-item label="数值">{{
            currentDetail.value
          }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentDetail.status)">{{
              currentDetail.status
            }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="描述">{{
            currentDetail.description
          }}</el-descriptions-item>
        </el-descriptions>

        <div class="mt-4">
          <h4 class="mb-2">趋势图</h4>
          <div ref="chartRef" style="width: 100%; height: 300px"></div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

// 查询表单数据
const queryForm = ref({
  dateRange: [],
  dataType: '',
  robotId: '',
  keyword: '',
  status: ''
})

// 选项数据
const dataTypeOptions = [
  { label: '温度数据', value: 'temperature' },
  { label: '湿度数据', value: 'humidity' },
  { label: '电量数据', value: 'battery' },
  { label: '运行状态', value: 'status' }
]

const robotOptions = [
  { label: '机器人A', value: 'robot_a' },
  { label: '机器人B', value: 'robot_b' },
  { label: '机器人C', value: 'robot_c' }
]

const statusOptions = [
  { label: '正常', value: 'normal' },
  { label: '异常', value: 'abnormal' },
  { label: '警告', value: 'warning' }
]

// 表格数据
const loading = ref(false)
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 详情对话框
const detailDialogVisible = ref(false)
const currentDetail = ref({})
const chartRef = ref(null)
let chart = null

// 获取状态对应的类型
const getStatusType = (status) => {
  const map = {
    normal: 'success',
    abnormal: 'danger',
    warning: 'warning'
  }
  return map[status] || 'info'
}

// 查询数据
const handleSearch = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 1000))
    tableData.value = Array(10)
      .fill(null)
      .map((_, index) => ({
        date: '2025-02-10 12:00:00',
        robotName: `机器人${String.fromCharCode(65 + (index % 3))}`,
        dataType: '温度数据',
        value: `${20 + Math.random() * 10}℃`,
        status: ['normal', 'abnormal', 'warning'][
          Math.floor(Math.random() * 3)
        ],
        description: '这是一条测试数据描述'
      }))
    total.value = 100
  } catch (error) {
    ElMessage.error('查询失败')
  } finally {
    loading.value = false
  }
}

// 重置表单
const queryFormRef = ref(null)
const resetForm = () => {
  queryFormRef.value?.resetFields()
}

// 导出数据
const handleExport = () => {
  ElMessage.success('数据导出成功')
}

// 刷新数据
const refreshData = () => {
  handleSearch()
}

// 显示详情
const showDetail = (row) => {
  currentDetail.value = row
  detailDialogVisible.value = true
  nextTick(() => {
    initChart()
  })
}

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return

  chart?.dispose()
  chart = echarts.init(chartRef.value)

  const option = {
    color: ['#4834d4'],
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: [820, 932, 901, 934, 1290, 1330, 1320],
        type: 'line',
        smooth: true
      }
    ]
  }

  chart.setOption(option)
}

// 处理分页
const handleSizeChange = () => {
  handleSearch()
}

const handleCurrentChange = () => {
  handleSearch()
}

// 数据分析
const handleAnalyze = (row) => {
  ElMessage.success(`开始分析 ${row.robotName} 的数据`)
}

onMounted(() => {
  handleSearch()
})
</script>

<style lang="scss" scoped>
.history-page {
  padding: 20px;

  .filter-card,
  .data-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    :deep(.el-card__header) {
      padding: 16px 20px;
      border-bottom: 1px solid #ebeef5;
    }
  }

  :deep(.el-form-item__label) {
    font-weight: 500;
  }

  :deep(.el-button--primary) {
    --el-button-bg-color: #4834d4;
    --el-button-border-color: #4834d4;
    --el-button-hover-bg-color: #5b48e5;
    --el-button-hover-border-color: #5b48e5;
    --el-button-active-bg-color: #3f2db8;
    --el-button-active-border-color: #3f2db8;
  }

  .data-detail {
    :deep(.el-descriptions) {
      padding: 16px;
      background-color: #fafafa;
      border-radius: 4px;
    }
  }
}

// 工具类
.mb-4 {
  margin-bottom: 16px;
}

.mt-4 {
  margin-top: 16px;
}

.mb-2 {
  margin-bottom: 8px;
}
</style>
